package com.wyc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyc.dto.Result;
import com.wyc.entity.Shop;
import com.wyc.mapper.ShopMapper;
import com.wyc.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyc.utils.CacheCline;
import com.wyc.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.wyc.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *

 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheCline cacheCline;

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 判断是否需要根据坐标查询
        if(x == null || y == null){
            // 不需要,直接去数据库里查
            Page<Shop> page = query().eq("type_id" , typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        // 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        // 查询redis 按照分页 距离 结果 shopId distance
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000), // 查询周围 5000米范围内的店铺
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)// 只能从0查询到结尾
                );
        // 解析ID
        if (results== null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(list.size() <= from){
            // 没有下一页 退出
            return Result.ok(Collections.emptyList());
        }
        // 截取from-end之间的内容
        List<Long> ids = new ArrayList<>(list.size());
        Map<String,Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result ->{
            // 获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 根据ID 查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id, " + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }

        // 返回
        return Result.ok(shops);
    }

    @Override
    public Result queryById(Long id) {
         //缓存穿透
         Shop shop = cacheCline.queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        // 互斥锁解决穿击
        // Shop shop = queryWithMutes(id);
        // 逻辑过期解决穿击(需要预热，提前设置缓存)
//        Shop shop = cacheCline.queryWithLogicalExpire(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
//        if (shop == null) {
//            return Result.fail("店铺不存在");
//        }

        return Result.ok(shop);
    }


//    //互斥锁解决缓存穿透
//    public Shop queryWithMutes(Long id) {
//        String key = CACHE_SHOP_KEY + id;
//        // 从redis获取缓存
//        String shopJson = stringRedisTemplate.opsForValue().get(key);
//        // 如果存在直接返回
//        if (StrUtil.isNotBlank(shopJson)) {
//
//            return JSONUtil.toBean(shopJson, Shop.class);
//        }
//        // 判断是否命中空值
//        if (shopJson != null) {
//            return null;
//        }
//        // 缓存重建
//        // 获取互斥锁
//        String lockKey = LOCK_SHOP_KEY + id;
//        Shop shop = null;
//        try {
//            boolean isLock = tryLock(lockKey);
//            if (!isLock) {
//                // 获取失败，休眠并且重试
//                Thread.sleep(50);
//                // 递归
//                return queryWithMutes(id);
//            }
//
//            // 去数据库中查询
//            shop = getById(id);
//            if (shop == null) {
//                // 将空值写入 redis
//                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
//                return null;
//            }
//            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        } finally {
//            // 释放互斥锁
//            unlock(lockKey);
//        }
//
//        return shop;
//    }


//    //逻辑过期解决缓存穿透
//    // 线程池
//    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

//    public Shop queryWithLogicalExpire(Long id) {
//        String key = CACHE_SHOP_KEY + id;
//        // 从redis获取缓存
//        String shopJson = stringRedisTemplate.opsForValue().get(key);
//        // 如果存在直接返回
//        if (StrUtil.isBlank(shopJson)) {
//
//            return null;
//        }
//        // 命中,把JSON 反序列化为对象
//        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
//        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
//        LocalDateTime expireTime = redisData.getExpireTime();
//        if (expireTime.isAfter(LocalDateTime.now())) {
//            // 未过期 直接返回店铺信息
//            return shop;
//        }
//        //  如果是过期了
//
//        String lockKey = LOCK_SHOP_KEY + id;
//        // 尝试获取锁
//        Boolean isLock = tryLock(lockKey);
//        // 判断是否成功获取锁
//        if (isLock) {
//            // 成功, 开启独立线程，实现缓存重写
//            CACHE_REBUILD_EXECUTOR.submit(() -> {
//                try {
//                    // 重建缓存
//                    this.saveShop2Redis(id, 20L);
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                } finally {
//                    // 释放锁
//                    unlock(lockKey);
//                }
//            });
//        }
//        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        return shop;
//    }

//    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
//        // 查询店铺信息
//        Shop shop = getById(id);
//
//        // 封装逻辑过期时间
//        RedisData redisData = new RedisData();
//        redisData.setData(shop);
//        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//        // 写入redis
//        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
//    }


    // 缓存击穿
//    public Shop queryWithPassThrough(Long id) {
//        String key = CACHE_SHOP_KEY + id;
//        // 从redis获取缓存
//        String shopJson = stringRedisTemplate.opsForValue().get(key);
//        // 如果存在直接返回
//        if (StrUtil.isNotBlank(shopJson)) {
//
//            return JSONUtil.toBean(shopJson, Shop.class);
//        }
//        // 判断是否命中空值
//        if (shopJson != null) {
//            return null;
//        }
//        // 去数据库中查询
//        Shop shop = getById(id);
//        if (shop == null) {
//            // 将空值写入 redis
//            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
//            return null;
//        }
//        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        return shop;
//    }

    @Override
    @Transactional
    public Result update(Shop shop) {

        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺ID不能为空");
        }
        // 更新数据库
        updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }

//    private boolean tryLock(String Key) {
//        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(Key, "1", 10, TimeUnit.SECONDS);
//        return BooleanUtil.isTrue(flag);
//    }
//
//    private void unlock(String Key) {
//        stringRedisTemplate.delete(Key);
//    }



}
